<template>
  <el-tabs v-model="activeName" type="border-card" @tab-click="tabClick">
    <el-tab-pane
      v-for="(face, index1) in afsInfo.afsFaceList"
      :key="index1"
      :label="face.faceName"
      :name="`${face.deviceId}-${face.faceFlag}`"
    >
      <el-row>
        <el-col :span="24">
          <PortTip class="mb-10" />
        </el-col>
        <el-col :span="24">
          <el-row
            class="segment-list-box"
            :gutter="8"
            style="max-height: 500px;
    overflow: hidden;
    overflow-y: auto;"
          >
            <el-col
              v-for="(port, index2) in face.portList"
              :key="index2"
              style="margin-top: 5px;"
              :span="2"
            >
              <div class="conn-content">
                <!-- A面 -->
                <div
                  :class="[
                    `color-${portIdKey[port.portId].status &&
                      portIdKey[port.portId].status.toLowerCase()}`,
                    'conn-item',
                    'topo-port',
                    { 'selected-port-link': port.selected }
                  ]"
                  @click="portChange(port, 'PORT')"
                >
                  {{ portIdKey[port.portId].name || port.portId }}
                </div>
                <!-- B面 -->
                <div
                  v-if="port.connPortId"
                  :class="[
                    `color-${portIdKey[port.connPortId].status &&
                      portIdKey[port.connPortId].status.toLowerCase()}`,
                    'conn-item',
                    { 'selected-port-link': port.conn_selected },
                    'port-item',
                    'topo-port',
                  ]"
                  @click="portChange(port, 'CONN_PORT')"
                >
                  {{ portIdKey[port.connPortId].name }}
                </div>
                <div v-else class="conn-item port-item">--</div>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-tab-pane>
  </el-tabs>
</template>
<script>
  import { deepClone } from '@/utils/common'
  import PortTip from './PortTip.vue'
  export default {
    components: { PortTip },
    props: {
      deviceInfo: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        activeName: 'first',
        afsInfo: {}, // 记录afs详情（端口，id，name等）
        portIdKey: {}, // key是portId，value是portName，用来反显对端端口的portName
        selectedPortList: [] // 记录选中的端口,selectedPortList[0]记录port，selectedPortList[1]记录conn_port
      }
    },
    mounted() {
      this.getAfsAllports()
      console.log(this.selectedPortList)
    },
    methods: {
      tabClick() {
        const oldSelectedPortList = deepClone(this.selectedPortList)
        this.selectedPortList = []
        this.afsInfo.afsFaceList.forEach(i => {
          if (`${i.deviceId}-${i.faceFlag}` === this.activeName) {
            i.portList.forEach(j => {
              j.selected = false
              j.conn_selected = false
              oldSelectedPortList.forEach((k, index) => {
                if (k.selectedPortId === j.portId) {
                  this.portChange(j, 'PORT')
                } else if (k.selectedPortId === j.connPortId) {
                  this.portChange(j, 'CONN_PORT')
                }
              })
              // 特殊情况需要处理，如果选择的是已经建立连接的2个端口，两次记录的selectedPortId会是同一个
              // 因为在一个对象里，selectedPortId的值每次被覆盖
              if (oldSelectedPortList.length === 2) {
                if (oldSelectedPortList[0].selectedPortId === j.portId) {
                  if (oldSelectedPortList[0].selectedPortId === oldSelectedPortList[1].selectedPortId) {
                    // 选择的是已经建立连接的端口
                    this.portChange(j, 'PORT')
                    this.portChange(j, 'CONN_PORT')
                  }
                }
              }
            })
          }
        })
      },
      portChange(currentPort, type) {
        console.log(currentPort, type)
        if (type === 'PORT') {
          // 当前面当前端口
          let hasIndex = 0
          // 先判断选择的端口是否已经被选中了
          hasIndex = this.selectedPortList.findIndex(
            i => i.selected && i.portId === currentPort.portId
          )
          if (hasIndex !== -1) {
            // 如果已经被选中，移除选中并将选中状态置为false
            this.selectedPortList.splice(hasIndex, 1)[0].selected = false
          } else {
            currentPort.selected = true
            currentPort.selectedPortId = currentPort.portId
            // A型设备有A和B面，A——A和B——B不能相连，只能A-B相连
            // B型设备只有B面，允许B-B相连
            // C型设备有A和B面，允许A——B和B——B这种连接方式，不允许A-A相连
            // D型（新C型）设备有A和B面，允许A——A和B——B和A——B相连
            // B面端口用partFlag = M来区分
            // 针对D型设备，不能用partFlag来区分，得用afsType = D来区分
            // partFlag=M代表设备有混合面，有混合面的允许同一面的B-B相连
            // afsType=D代表D型设备，允许同一面的A-A相连
            if (currentPort.partFlag === 'M' || currentPort.afsType === 'D') {
              this.selectedPortList.push(currentPort)
            } else {
              // 除了以上情况，如果用户选择同一面的两个类型的端口，需要把前一个同类型的端口给取消选中
              let index = 0
              index = this.selectedPortList.findIndex(
                i =>
                  i.selected &&
                  i.partFlag === currentPort.partFlag &&
                  i.portId !== currentPort.portId
              )
              if (index !== -1) {
                this.selectedPortList.splice(index, 1)[0].selected = false
              }
              // 把后选择的push到集合里
              this.selectedPortList.push(currentPort)
            }
          }
        } else if (type === 'CONN_PORT') {
          // 当前面对端端口
          let hasIndex = 0
          hasIndex = this.selectedPortList.findIndex(
            i => i.conn_selected && i.connPortId === currentPort.connPortId
          )
          if (hasIndex !== -1) {
            this.selectedPortList.splice(hasIndex, 1)[0].conn_selected = false
          } else {
            currentPort.conn_selected = true
            currentPort.selectedPortId = currentPort.connPortId
            if (this.portIdKey[currentPort.connPortId].partFlag === 'M' || currentPort.afsType === 'D') {
              this.selectedPortList.push(currentPort)
            } else {
              let index = 0
              index = this.selectedPortList.findIndex(
                i =>
                  i.conn_selected &&
                  this.portIdKey[i.connPortId].partFlag ===
                  this.portIdKey[currentPort.connPortId].partFlag &&
                  i.connPortId !== currentPort.connPortId
              )
              if (index !== -1) {
                this.selectedPortList.splice(index, 1)[0].conn_selected = false
              }
              this.selectedPortList.push(currentPort)
            }
          }
        }
        if (this.selectedPortList.length > 2) {
          const deletePort = this.selectedPortList.shift()
          if (deletePort.selected) {
            deletePort.selected = false
          } else if (deletePort.conn_selected) {
            deletePort.conn_selected = false
          }
        }
        this.$forceUpdate()
        this.$emit('change', this.selectedPortList)
      },
      // 根据设备id查询
      getAfsAllports() {
        this.afsInfo = {}
        this.portIdKey = {}
        this.selectedPortList = []
        if (!this.deviceInfo.afsFaceList) return
        this.deviceInfo.afsFaceList.forEach(ele1 => {
          ele1.portList.forEach(ele2 => {
            ele2.portName = `${ele1.faceFlag.replace(/M/g, 'B')}-${
              ele2.partPortNo
            }`
            ele2.afsType = this.deviceInfo.afsType
            this.portIdKey[ele2.portId] = {
              name: `${ele1.faceFlag.replace(/M/g, 'B')}-${
                ele2.partPortNo
              }`,
              status: ele2.status,
              partFlag: ele2.partFlag
            }
            ele2.selected = false
            ele2.conn_selected = false
          })
        })
        this.afsInfo = { ...this.deviceInfo }
        this.activeName = `${this.afsInfo.afsFaceList[0].deviceId}-${
          this.afsInfo.afsFaceList[0].faceFlag
        }`
      },
      portListShif() {
        const deletePort = this.selectedPortList.shift()
        if (deletePort.selected) {
          deletePort.selected = false
        } else if (deletePort.conn_selected) {
          deletePort.conn_selected = false
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
.conn-content {
  user-select: none;
  border-width: 1px;
  border-style: solid;
  cursor: pointer;
  .conn-item {
    text-align: center;
    padding: 5px 0;
  }
  .conn-item + .conn-item {
    border-top-width: 1px;
    border-top-style: dotted;
  }
}
.selected-port-link {
  background: #122f85;
}
</style>
